/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.easoft.code.pos.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;

/**
 *
 * @author Eliu
 */
public class DBConnection {

    private static DataSource dataSource;
    private static String DRIVER_NAME;
    private static String URL;
    private static String UNAME;
    private static String PWD;

    public static Connection getConnection() throws SQLException {
        if (dataSource == null) {
            try {
                Properties p = new Properties();
                p.load(DBConnection.class.getResourceAsStream("/props.database.properties"));
                DRIVER_NAME = p.getProperty("driverName");
                URL = p.getProperty("url");
                UNAME = p.getProperty("uname");
                PWD = p.getProperty("pwd");

                dataSource = setupDataSource();
            } catch (IOException ex) {
                Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return dataSource.getConnection();
    }

    private static DataSource setupDataSource() {
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        try {
            cpds.setDriverClass(DRIVER_NAME);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        cpds.setJdbcUrl(URL);
        cpds.setUser(UNAME);
        cpds.setPassword(PWD);
        cpds.setMinPoolSize(5);
        cpds.setAcquireIncrement(5);
        cpds.setMaxPoolSize(20);
        return cpds;
    }
}
